import { useMutation, useQueryClient } from '@tanstack/react-query';
import { message, Modal } from 'antd';
import React from 'react';

import api from '@/apis/api';
import localINFO from '@/utils/localInfo';

interface DeleteIpAddressProps {
  title: string;
  visible: boolean;
  setVisible: (visible: boolean) => void;
  total: number;
  page: number;
  pageSize: number;
  setPage: (page: number) => void;
  recordId?: number;
}

const DeleteIpAddress: React.FC<DeleteIpAddressProps> = ({
  title,
  visible,
  setVisible,
  recordId,
  total,
  page,
  pageSize,
  setPage,
}) => {
  const queryClient = useQueryClient();

  const DeleteWhiteList = useMutation({
    mutationFn: (params: any) => api.DeleteWhiteList(params),
    onSuccess: (res: any) => {
      if (res?.success) {
        message.success('删除成功');
        if (total && page > total / pageSize && total % pageSize === 1 && page > 1) {
          setPage(page - 1);
        }
      } else {
        message.error(`删除失败, ${res?.message}`);
      }
    },
    onError: () => {
      message.error('删除失败');
    },
    onSettled: () => queryClient.invalidateQueries({ queryKey: ['getWhiteListData'] }),
    mutationKey: ['getWhiteListData'],
  });

  const DeleteBlackList = useMutation({
    mutationFn: (params: any) => api.DeleteBlackList(params),
    onSuccess: (res: any) => {
      if (res?.success) {
        message.success('删除成功');
        if (total && page > total / pageSize && total % pageSize === 1 && page > 1) {
          setPage(page - 1);
        }
      } else {
        message.error(`删除失败, ${res?.message}`);
      }
    },
    onError: () => {
      message.error('删除失败');
    },
    onSettled: () => queryClient.invalidateQueries({ queryKey: ['getBlackListData'] }),
    mutationKey: ['getBlackListData'],
  });

  const handleDeleteOk = async () => {
    if (recordId) {
      if (title === '白名单') {
        DeleteWhiteList.mutate({
          id: recordId,
        });
      } else {
        DeleteBlackList.mutate({
          id: recordId,
        });
      }
    }
    setVisible(false);
  };

  const handleDeleteCancel = () => {
    setVisible(false);
  };

  return (
    <>
      <Modal
        title={`删除${title}`}
        open={visible}
        onOk={handleDeleteOk}
        onCancel={handleDeleteCancel}
        cancelText="取消"
        okText="确定"
        okButtonProps={{ disabled: localINFO.getRoleId() !== 1 }}
      >
        <p style={{ marginLeft: 12, color: 'red' }}>
          注意：添加或删除白名单时，请保证至少有一条管理端可用IP！
        </p>
        <p style={{ marginLeft: 24 }}>您确定要删除该地址吗？</p>
      </Modal>
    </>
  );
};

export default DeleteIpAddress;
